#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time      :2021/7/15 15:00
# @Author    :cjw
"""配置文件"""
import secrets
from os.path import join, dirname
from typing import List

from pydantic import AnyHttpUrl, BaseSettings, EmailStr, validator

from app.utils import util


class Settings(BaseSettings):
    API_V1_STR: str = '/api/api_v1'  # 接口地址前缀

    BASE_PATH: str = dirname(dirname(__file__))  # 根目录，app目录

    LOG_PATH: str = join(BASE_PATH, 'log')  # 日志路径

    ACCESS_TOKEN_JWT_SUBJECT = 'access'  # 访问令牌信息
    PASSWORD_RESET_JWT_SUBJECT = 'preset'  # 密码重置令牌信息

    # jwt加密密钥，token_urlsafe: 返回随机字节为nbytes(默认32位)的URL安全文本字符串，以Base64编码
    # SECRET_KEY: str = secrets.token_urlsafe(64)
    SECRET_KEY: str = 'rJ0xu7hjrj_Kp-Eff_jR7W45c_a8YB8DnuU9c73W7Nsl6t6D5G_sTDa09xZZnGmHxLrC3by-nlCkh4bBofQdLQ'

    ALGORITHM: str = 'HS256'  # 加密算法方式

    # 令牌过期时间：60 minutes * 24 hours * 7 days = 7 days
    ACCESS_TOKEN_EXPIRE_MINUTES: int = 60 * 24 * 7

    SERVER_NAME: str = None
    SERVER_HOST: AnyHttpUrl = f'http://{util.get_local_ip()}'

    # 跨域访问限制，域：协议+域名+端口
    BACKEND_CORS_ORIGINS: List[AnyHttpUrl] = []

    # pre: 是否应在标准验证器之前调用此验证器（否则在之后调用）
    # e.g: '["http://localhost", "http://localhost:4200", "http://localhost:3000", \
    # "http://localhost:8080", "http://local.dockertoolbox.tiangolo.com"]'
    @validator('BACKEND_CORS_ORIGINS', pre=True)
    def assemble_cors_origins(cls, v):
        """
        对字符串列表域进行分割处理成列表
        :param v: 未处理的数据：BACKEND_CORS_ORIGINS
        :return:
        """
        if isinstance(v, str) and not v.startswith('['):
            return [i.strip() for i in v.split(',')]
        return v

    PROJECT_NAME: str = 'FastAPI框架验证项目'

    # 数据库连接方法
    SQLALCHEMY_DATABASE_URL: str = 'mariadb+pymysql://root:123456@127.0.0.1:3306/fastapi'

    # 邮件相关
    SMTP_SSL: bool = True
    SMTP_PORT: int = 465
    SMTP_HOST: str = 'smtp.qq.com'
    SMTP_USER: str = '1031901787@qq.com'
    SMTP_PASSWORD: str = 'yjeamisqrswxbeea'
    EMAILS_FROM_EMAIL: EmailStr = '1031901787@qq.com'
    EMAILS_FROM_NAME: str = None

    @validator('EMAILS_FROM_NAME')
    def get_project_name(cls, v, values):
        if not v:
            return values['PROJECT_NAME']
        return v

    # 重置密码邮件过期时间
    EMAIL_RESET_TOKEN_EXPIRE_HOURS: int = 48
    # 邮件模板地址
    EMAIL_TEMPLATES_DIR: str = join(BASE_PATH, 'email-templates', 'build')
    EMAILS_ENABLED: bool = False

    @validator('EMAILS_ENABLED', pre=True)
    def get_emails_enabled(cls, v, values):
        return bool(
            values.get('SMTP_HOST')
            and values.get('SMTP_PORT')
            and values.get('EMAILS_FROM_EMAIL')
        )

    # 测试用户邮箱
    EMAIL_TEST_USER: EmailStr = '18367157420@163.com'

    # 超级用户账号密码
    FIRST_SUPERUSER: EmailStr = 'cjw@qq.com'
    FIRST_SUPERUSER_PASSWORD: str = '123456'

    # 是否开启用户注册
    USERS_OPEN_REGISTRATION: bool = False


settings = Settings()

if __name__ == '__main__':
    print(settings.SECRET_KEY)